//
//  ExaminationPaperViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/2.
//

#import "ExaminationPaperViewController.h"
#import "ExaminationPaperListCell.h"
#import "ExaminationPaperBeginCell.h"
#import "ExaminationPaperScoreCell.h"
#import "ExamQuestionsViewController.h"
#import "ExamPaperTypeListManager.h"
#import "ExamPaperTypeListModel.h"
#import "ExamPaperResultManager.h"
#import "ExamPaperResultModel.h"
#import "ExamPaperResultListModel.h"
#import "ExamWriteViewController.h"
#import "ExamPaperResetManager.h"

@interface ExaminationPaperViewController ()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate,ExaminationPaperBeginCellDelegate,ExaminationPaperListCellDelegate,ExaminationPaperScoreCellDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)ExamPaperTypeListManager *typeListManager;
@property(nonatomic,strong)ExamPaperResultManager *resultManager;
@property(nonatomic,strong)ExamPaperResultModel *resultModel;
@property(nonatomic,strong)ExamPaperResetManager *resetManager;
@property(nonatomic,strong)ExamPaperTypeListModel *resetTypeListModel;
@property(nonatomic,assign)BOOL isFinishRefresh;
@property(nonatomic,strong)UILabel *titleLabel;

@end

@implementation ExaminationPaperViewController

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(ExamPaperTypeListManager *)typeListManager{
    if(!_typeListManager){
        _typeListManager = [[ExamPaperTypeListManager alloc]init];
        _typeListManager.delegate = self;
    }
    return _typeListManager;
}

-(ExamPaperResultManager *)resultManager{
    if(!_resultManager){
        _resultManager = [[ExamPaperResultManager alloc]init];
        _resultManager.delegate = self;
    }
    return _resultManager;
}

-(ExamPaperResetManager *)resetManager{
    if(!_resetManager){
        _resetManager = [[ExamPaperResetManager alloc]init];
        _resetManager.delegate = self;
    }
    return _resetManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createUI];
    [self loadTypeListData];
    [self loadPaperResult];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshPaperTypeData) name: @"refreshPaperTypeData" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(commitExamSuccess:) name: @"CommitExamSuccess" object:nil];
       

}

#pragma mark - 交卷成功刷新数据
-(void)commitExamSuccess:(NSNotification*)notifi{
    NSString *isexam = notifi.object;
    if(isexam&&[isexam isEqualToString:@"1"]){
        self.isFinishRefresh = YES;
        [self loadPaperResult];
    }else{
        [self loadTypeListData];
    }
}

#pragma mark - 答完题后刷新专项数据
-(void)refreshPaperTypeData{
    [self loadTypeListData];
}

#pragma mark - 获取专项数据
-(void)loadTypeListData{
    //n1-3 @[@"文字词汇",@"语法",@"阅读",@"听力"];
    //高考 @[@"听力",@"单选",@"阅读",@"写作"]
    //考研 @[@"基础知识",@"阅读",@"写作"]
    self.typeListManager.paperId = self.listModel.paperId;
    [self.typeListManager loadData];
}

#pragma mark - 获取考试整套成绩
-(void)loadPaperResult{
    self.resultManager.paperId = self.listModel.paperId;
    [self.resultManager loadData];
}

#pragma mark - 重置
-(void)resetPaperWithModel:(ExamPaperTypeListModel*)model{
    self.resetTypeListModel = model;
    self.resetManager.paperId = model.paperId;
    self.resetManager.ptId = model.ptId;
    [self.resetManager loadData];
}

-(void)createUI{
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.textColor = KFontBlackColor;
    self.titleLabel.font = JPUIFontPingFangSCMedium(17);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = self.listModel.name;
    [self.customNavigationBar addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@40);
        make.right.mas_equalTo(@-40);
        make.bottom.mas_equalTo(@-5);
        make.height.mas_equalTo(@34);
    }];
        
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = KbgColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"ExaminationPaperListCell") forCellReuseIdentifier:@"ExaminationPaperListCell"];
    [self.tableView registerClass:NSClassFromString(@"ExaminationPaperBeginCell") forCellReuseIdentifier:@"ExaminationPaperBeginCell"];
    [self.tableView registerClass:NSClassFromString(@"ExaminationPaperScoreCell") forCellReuseIdentifier:@"ExaminationPaperScoreCell"];
    [self.view addSubview:self.tableView];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.tableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
            [self.tableView reloadData];
        });
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        ExaminationPaperListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExaminationPaperListCell"];
        cell.delegate = self;
        cell.currentAvailableWidth = self.currentAvailableWidth;
        if(indexPath.row == 0){
            [cell refreshWithIsBottom:NO andIsTop:YES];
        }else if (indexPath.row == self.dataArr.count-1){
            [cell refreshWithIsBottom:YES andIsTop:NO];
        }else{
            [cell refreshWithIsBottom:NO andIsTop:NO];
        }
        if(indexPath.row < self.dataArr.count){
            ExamPaperTypeListModel *model = self.dataArr[indexPath.row];
            cell.model = model;
        }
        return cell;
    }
    if(self.resultModel&&[self.resultModel.isExam isEqualToString:@"1"]){
        ExaminationPaperScoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExaminationPaperScoreCell"];
        cell.delegate = self;
        cell.time = self.listModel.time;
        cell.resultModel = self.resultModel;
        return cell;
    }
    ExaminationPaperBeginCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExaminationPaperBeginCell"];
    cell.delegate = self;
    cell.model = self.listModel;
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return  self.dataArr.count;
    }
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return 62;
    }
    if(self.resultModel&&[self.resultModel.isExam isEqualToString:@"1"]){
        return 200+48*self.resultModel.list.count;
    }
    return 120;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,52)];
    headerView.backgroundColor = KbgColor;
    UIImageView *bottomImageView = [[UIImageView alloc]initWithFrame:CGRectMake(18,27,36,10)];
    bottomImageView.backgroundColor = [UIColor clearColor];
    bottomImageView.image = [UIImage imageNamed:@"discover_question_title_bottom"];
    [headerView addSubview:bottomImageView];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,16,self.currentAvailableWidth-40,24)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = JPUIFontPingFangSCMedium(17);
    titleLabel.textColor = KFontBlackColor;
    if(section == 0){
        titleLabel.text = @"专项";
    }else{
        titleLabel.text = @"整套";
    }
    [headerView addSubview:titleLabel];
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 52;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,4)];
    if(section == 1){
        footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYMBottomH);
    }
    footerView.backgroundColor = KbgColor;
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 1){
        return kYMBottomH;
    }
    return 4;
}

#pragma mark - 专项开始测试
-(void)optionTestTap:(ExaminationPaperListCell *)cell{
    if([cell.model.typeId isEqualToString:@"36"]){
        //写作
        ExamWriteViewController *vc = [[ExamWriteViewController alloc]init];
        vc.paperModel = self.listModel;
        vc.typeModel = cell.model;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        if([cell.model.isFinish isEqualToString:@"1"]){
            //重新测试
            [self resetPaperWithModel:cell.model];
        }else{
            ExamQuestionsViewController *vc = [[ExamQuestionsViewController alloc]init];
            vc.paperModel = self.listModel;
            vc.testType = 0;
            vc.typeModel = cell.model;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark - 正确率点击
-(void)correctRateTap:(ExaminationPaperListCell *)cell{
    ExamQuestionsViewController *vc = [[ExamQuestionsViewController alloc]init];
    vc.paperModel = self.listModel;
    vc.testType = 3;
    vc.typeModel = cell.model;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 开始考试
- (void)testTap:(ExaminationPaperBeginCell *)cell{
    ExamQuestionsViewController *vc = [[ExamQuestionsViewController alloc]init];
    vc.typeArr = self.dataArr;
    vc.paperModel = self.listModel;
    vc.testType = 1;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 重新考试
-(void)scoreTestTap:(ExaminationPaperScoreCell *)cell{
    
    ExamQuestionsViewController *vc = [[ExamQuestionsViewController alloc]init];
    vc.typeArr = self.dataArr;
    vc.paperModel = self.listModel;
    vc.testType = 1;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 查看试卷解析
-(void)checkAnalysisTap:(ExaminationPaperScoreCell *)cell{
    ExamQuestionsViewController *vc = [[ExamQuestionsViewController alloc]init];
    vc.paperModel = self.listModel;
    vc.typeArr = self.dataArr;
    vc.testType = 2;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.typeListManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [ExamPaperTypeListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        [self.tableView reloadData];
    }
    
    if([manager isEqual:self.resultManager]){
        NSDictionary *dic = manager.response.content;
        self.resultModel = [ExamPaperResultModel mj_objectWithKeyValues:dic[@"data"]];
        if(self.isFinishRefresh == YES){
            self.isFinishRefresh = NO;
            NSMutableArray *rarr = [NSMutableArray array];
            [rarr addObject:self.resultModel.sumScore?self.resultModel.sumScore:@"0"];
            [rarr addObject:self.listModel.paperId?self.listModel.paperId:@""];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"examScoreRefresh" object:rarr];
        }
        if([self.resultModel.isExam isEqualToString:@"1"]){
            NSArray *arr = [ExamPaperResultListModel mj_objectArrayWithKeyValuesArray:self.resultModel.list];
            self.resultModel.list = arr;
        }
        [self.tableView reloadData];
    }
    
    if([manager isEqual:self.resetManager]){
        for(NSInteger i = 0;i < self.dataArr.count;i++){
            ExamPaperTypeListModel *model = self.dataArr[i];
            if([model.ptId isEqualToString:self.resetManager.ptId]){
                model.isFinish = @"0";
                model.correctPercent = @"";
                [self.dataArr replaceObjectAtIndex:i withObject:model];
                break;
            }
        }
        [self.tableView reloadData];
        ExamQuestionsViewController *vc = [[ExamQuestionsViewController alloc]init];
        vc.paperModel = self.listModel;
        vc.testType = 0;
        vc.typeModel = self.resetTypeListModel;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}



@end
